<template>
  <div class="app-container">
    <!--顶部搜索条件-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="检测商品" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入检测商品"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测结果" prop="result">
        <el-select
          v-model="queryParams.result"
          placeholder="请选择检测结果"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.check_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上报状态" prop="reportStatus">
        <el-select
          v-model="queryParams.reportStatus"
          placeholder="请选择上报状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.check_report_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检测时间">
        <el-date-picker
          v-model="checkTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="数据来源" prop="dataSource">
        <el-select
          v-model="queryParams.dataSource"
          placeholder="请选择数据来源"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.check_data_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--顶部操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['check:detection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['check:detection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['check:detection:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['check:detection:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--表格-->
    <el-table v-loading="loading" :data="detectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" prop="goodsName" align="center" width="120" />
      <el-table-column label="检测项目" prop="itemName" align="center" width="200" />
      <el-table-column label="检测时间" prop="checkTime" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测结果" prop="result" align="center" width="120">
        <template slot-scope="scope">
          <span>
            {{ selectDictLabels(dict.type.check_result,scope.row.result) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="上报状态" prop="reportStatus" align="center" width="150">
        <template slot-scope="scope">
          <span>
            {{ selectDictLabels(dict.type.check_report_status,scope.row.reportStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="数据来源" prop="dataSource" align="center" width="120">
        <template slot-scope="scope">
          <span>
            {{ selectDictLabels(dict.type.check_data_source,scope.row.dataSource) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="检测值" prop="checkValue" align="center" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" min-width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['check:detection:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['check:detection:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleReport(scope.row)"
            v-hasPermi="['check:detection:report']"
          >上报快件一件事</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测商品" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请填写检测商品" maxlength="32"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项目" prop="itemIds">
              <el-select
                v-model="form.itemIds"
                multiple
                filterable
                placeholder="请选择检测项目"
                style="width: 100%"
              >
                <el-option
                  v-for="item in this.selectItemList"
                  :key="item.itemId"
                  :label="item.itemName"
                  :value="item.itemId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测时间" prop="checkTime">
              <el-date-picker
                v-model="form.checkTime"
                type="datetime"
                style="width: 100%;"
                placeholder="选择日期时间"
                default-time="12:00:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测值" prop="checkValue">
              <el-input v-model="form.checkValue" placeholder="请填写检测值" maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(item,index) in form.itemList" :key="item.itemId">
          <el-col :span="12">
            <el-form-item
              :label="'项目'+(index+1)"
              :prop="'itemList.' + index + '.itemName'"
              :rules="{ required: true, message: '检测项目不能为空', trigger: 'blur' }"
            >
              <el-input :disabled="true" v-model="item.itemName" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="检测结果"
              :prop="'itemList.' + index + '.result'"
              :rules="{ required: true, message: '检测结果不能为空', trigger: 'blur' }"
            >
              <el-select v-model="item.result" placeholder="请选择检测结果" style="width:100%" @change="handleResult">
                <el-option
                  v-for="opt in dict.type.check_result"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="检测结果" prop="result">
              <el-radio-group :disabled="true" v-model="form.result">
                <el-radio
                  v-for="dict in dict.type.check_result"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="" :visible.sync="detailOpen" width="800px" :close-on-click-modal="false">
      <el-descriptions class="margin-top" title="检测详情" :column="2" border>
        <el-descriptions-item label="检测商品">{{detailData.goodsName}}</el-descriptions-item>
        <el-descriptions-item label="检测项目">{{detailData.itemName}}</el-descriptions-item>
        <el-descriptions-item label="检测时间">{{parseTime(detailData.checkTime)}}</el-descriptions-item>
        <el-descriptions-item label="检测值">{{detailData.checkValue}}</el-descriptions-item>
        <el-descriptions-item label="检测结果" :span="2">
          <template slot="label">
            检测结果
          </template>
          <el-tag type="success" v-if="detailData.result === '1'">合格</el-tag>
          <el-tag type="danger" v-if="detailData.result === '2'">不合格</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{detailData.remark}}</el-descriptions-item>
      </el-descriptions>



      <el-descriptions title="检测项目详情" :column="2" border class="margin-top" style="margin-top: 20px">
        <template v-for="(item, index) in detailData.itemList">
          <el-descriptions-item :key="index + 'itemName'">
            <template slot="label">
              检测项目{{ index + 1 }}
            </template>
            <span>{{ item.itemName }}</span>
          </el-descriptions-item>


          <el-descriptions-item :key="index + 'result'">
            <template slot="label">
              检测结果
            </template>
            <el-tag type="success" v-if="item.result === '1'">合格</el-tag>
            <el-tag type="danger" v-if="item.result === '2'">不合格</el-tag>
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :close-on-click-modal="false">
      <el-upload ref="upload" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess"
                 :auto-upload="false"
                 :limit="1"
                 style="height: 260px"
                 drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>

      <el-descriptions title="导入结果" :column="3" style="margin-top: 20px">
        <el-descriptions-item label="上传条数">{{upload.uploadTotal}}</el-descriptions-item>
        <el-descriptions-item label="成功条数">{{upload.successTotal}}</el-descriptions-item>
        <el-descriptions-item label="失败条数">{{upload.errorTotal}}</el-descriptions-item>
      </el-descriptions>
      <el-button type="text" size="mini" @click="exportErrorFile()">失败文件导出</el-button>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">上 传</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDetection, delDetection, getDetection, listDetection} from "@/api/check/detection";
import { listCheckItemAll} from "@/api/check/item";
import {getToken} from "@/utils/auth";

export default {
  name: "detectionIndex",
  dicts: ['check_result','check_report_status','check_data_source'],
  data(){
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        result: undefined,
        dataSource: undefined
      },
      showSearch: true,
      checkTime: [],
      detectionList: [],
      total: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      loading: false,
      title: "",
      open: false,
      form: {},
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          { min: 2, max: 32, message: '商品名称长度必须介于 2 和 32 之间', trigger: 'blur' }
        ],
        itemIds: [
          { required: true, message: "检测项目不能为空", trigger: "blur" }
        ],
        checkTime: [
          { required: true, message: "检测时间不能为空", trigger: "blur" }
        ],
        result: [
          { required: true, message: "检测结果不能为空", trigger: "blur" }
        ],
      },
      itemList: [],
      selectItemList: [],
      detailOpen: false,
      detailData: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/check/detection/importData",

        //上传文件返回id
        uploadId: "",
        //上传总数
        uploadTotal: 0,
        //上传成功数量
        successTotal: 0,
        //上传失败数量
        errorTotal: 0,
        //上传结果弹窗
        resultOpen: false,
      },
    }
  },
  watch: {
    'form.itemIds'(newVal) {
      const oldMap = {}
      this.form.itemList.forEach(f => { oldMap[f.itemId] = f.result })
      this.form.itemList = this.selectItemList
        .filter(opt => newVal.includes(opt.itemId))
        .map(opt => ({
          itemId: opt.itemId,
          itemName: opt.itemName,
          result: oldMap[opt.itemId] || ''
        }))
      this.form.itemId = this.form.itemList.map(item => item.itemId).join(',')
      this.form.itemName = this.form.itemList.map(item => item.itemName).join(',')
    }
  },
  created() {
    this.initCheckTime()
    this.getList()
  },
  methods: {
    initCheckTime(){
      // 使用
      const today = new Date();
      const endTime = this.formatDate(today);

      const start = new Date();
      start.setDate(today.getDate() - 6);
      const startTime = this.formatDate(start);
      this.checkTime = [startTime,endTime]
    },
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    getList(){
      this.loading = true
      listDetection(this.addDateTimeRange(this.queryParams,this.checkTime)).then(response => {
        this.detectionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleQuery(){
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery(){
      this.checkTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    reset(){
      this.form = {
        goodsName: "",
        itemId: "",
        itemName: "",
        result: "",
        checkTime: new Date(),
        checkValue: "",
        remark: "",
        itemIds: [],
        itemList: []
      }
    },
    handleAdd(){
      this.reset()
      listCheckItemAll().then(response => {
        this.selectItemList = response.data
        this.open = true
        this.title = "录入检测"
      })
    },
    handleDelete(row){
      const ids = row.id || this.ids
      const message = row.id ? "是否删除当前数据项？" : "是否删除当前选中数据？"
      const h = this.$createElement;
      const VNode = h("div", [
        h("p", message),
        h("p", { style: "color:red;margin-top:8px;" },"注意：已上报的数据并不会从快检一件事删除。")
      ]);
      // 把 vnode 传入封装方法
      this.$modal.confirmVNode(VNode, { title: "删除提示"})
        .then(function() {
          return delDetection(ids)
        }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {});
    },
    handleImport(){
      this.$modal.msgWarning("功能开发中，敬请期待")
      // this.upload.title = "检测导入"
      // this.resetUploadResult()
      // this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      //设置返回值
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.upload.uploadId = response.data.uploadId
      this.upload.uploadTotal = response.data.uploadTotal
      this.upload.successTotal = response.data.successTotal
      this.upload.errorTotal = response.data.errorTotal
    },
    resetUploadResult(){
      this.upload.uploadId = ""
      this.upload.uploadTotal = 0
      this.upload.successTotal = 0
      this.upload.errorTotal = 0
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('check/detection/importTemplate', {
      }, `检测导入模板_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.resetUploadResult()
      this.$refs.upload.submit()
    },
    exportErrorFile(){
      if (this.upload.uploadId === ""){
        this.$modal.msgWarning("未上传数据，请先上传")
      }else {
        this.$modal.msgWarning("导出失败文件")
      }
    },
    handleExport(){
      this.$modal.msgWarning("功能开发中，敬请期待")
    },
    handleReport(){
      this.$modal.msgWarning("功能开发中，敬请期待")
    },
    handleResult(){
      let handleResult = "1";
      this.form.itemList.forEach(o => {
        if (o.result === "2"){
          handleResult = "2";
        }
      })
      this.$set(this.form, 'result', handleResult);
    },
    submitForm: function (){
      this.$refs["form"].validate(valid => {
        if (valid){
          addDetection(this.form).then(response => {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel(){
      this.open = false
      this.reset()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleDetail(row){
      this.detailData = {}
      const id = row.id || this.ids
      getDetection(id).then(response => {
        this.detailData = response.data
        this.detailOpen = true
      })
    }
  }
}
</script>

<style scoped>

</style>
